<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>股票监控系统</title>
    <style> 
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            body {
                background-color: #000;
                color: #fff;
                font-family: Arial, sans-serif;
                font-size: 16px;
            }

            .container {
                width: 100%;
                height: 100%;
                display: flex;
            }

            .left-panel {
                width: 330px;
                height: 100%;
                display: flex;
                flex-direction: column;
                border-right: 1px solid #333;
                align-items:stretch;
            }

            .block-table-container {
                height: 30%;
                overflow: auto;
                border: 1px solid #333;
            }

            .stock-table-container {
                height: 70%;
                overflow: auto;
                border: 1px solid #333;
                margin-top: -1px;
            }

            .right-panel {
                width: 80%;
                height: 100%;
                position: relative;
            }

            table {
                width: 100%;
                border-collapse: collapse;
                font-size: 16px;
            }

            th, td {
                padding: 4px 8px;
                border-bottom: 1px solid #333;
            }

            td:nth-child(2),
            td:nth-child(3),
            td:nth-child(4) {
                text-align: right;
            }

            th:nth-child(2),
            th:nth-child(3),
            th:nth-child(4) {
                text-align: right;
            }

            td:first-child,
            th:first-child {
                text-align: left;
            }

            .chart-controls {
                position: absolute;
                top: 0;
                left: 0;
                z-index: 100;
            }

            .chart-type-switch {
                display: flex;
                gap: 0;
                position: absolute;
                top: 0;
                left: 0;
                z-index: 100;
            }

            .chart-type-switch button {
                background: #1a1a1a;
                border: 1px solid #333;
                border-right: none;
                color: #fff;
                padding: 2px 12px;
                cursor: pointer;
                font-size: 16px;
                white-space: nowrap;
                writing-mode: horizontal-tb;
                letter-spacing: normal;
                width: auto;
            }

            .chart-type-switch button:last-child {
                border-right: 1px solid #333;
            }

            .chart-type-switch button.active {
                background: #333;
            }

            .chart-container {
                /* width: 100%;
                height: 100%; */
                margin-top: 30px;
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                grid-template-rows: repeat(3, 1fr);
                gap: 1px;
            }

            .chart {
                position: relative;
                border: 1px solid #333;
                background: #000;
                width: 600px;
                height: 300px;
            }

            .chart-header {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 2px 8px;
                height: 24px;
                border-bottom: 1px solid #333;
                background: #000;
                z-index: 1;
            }

            .chart-title {
                font-size: 16px;
                font-weight: normal;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            .chart-info {
                display: flex;
                gap: 15px;
                font-size: 16px;
            }

            .price-up {
                color: #ff0000;
            }

            .price-down {
                color: #00ff00;
            }

            .selected {
                background-color: #2a2a2a;
            }

            .volume-bar {
                position: absolute;
                bottom: 0;
                width: 100%;
                height: 20%;
                opacity: 0.3;
            }

            ::-webkit-scrollbar {
                width: 6px;
                height: 6px;
            }

            ::-webkit-scrollbar-track {
                background: #1a1a1a;
            }

            ::-webkit-scrollbar-thumb {
                background: #333;
            }

            ::-webkit-scrollbar-thumb:hover {
                background: #444;
            }

            .chart canvas {
                width: 100%;
                height: calc(100% - 24px);
                margin-top: 24px;
            }

            /* 板块叠加容器 */
            .block-overlay-container {
                /* position: relative; */
                box-sizing: border-box;  
                width: 600px;
                /* width: 80%; height: 211px; */
            }

            /* 叠加模式下的图表容器 */
            .chart-container.overlay-mode {
                overflow-y: auto;
                overflow-x: hidden;
                /* display: block; */
            }

            /* 叠加图表样式 */
            .overlay-chart {
                background-color: #000000; /* 背景色改为纯黑 */
                border: 1px solid #333;
                border-radius: 4px;
                /* position: relative; */
                width: 100%;
                height: 300px;
                /* display: flex; */
                flex-direction: column;
            }

            .overlay-chart canvas {
                flex: 1;
                min-height: 0;
                min-width: 0;
            }

            /* 自定义HTML图例容器 */
            .chart-wrapper {
                display: flex;
                flex: 1;
                min-height: 0;
            }

            .html-legend {
                width: 130px; /* 为图例分配固定宽度 */
                padding-left: 10px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                font-size: 14px;
            }

            .legend-item {
                display: flex;
                align-items: center;
                margin-bottom: 8px; /* 项目间距 */
            }

            .legend-color-box {
                width: 12px;
                height: 12px;
                margin-right: 8px;
                flex-shrink: 0;
            }

            .legend-label-name {
                color: #ffffff; /* 名称设置为白色 */
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis; /* 超长时显示省略号 */
            }

            .legend-label-change {
                margin-left: auto; /* 将涨跌幅推到最右侧 */
                padding-left: 5px;
                font-weight: bold;
            }

            /* 叠加图表标题样式 */
            .overlay-chart-title {
                color: #fff;
                font-size: 14px;
                padding: 0 8px;
                border-bottom: 1px solid #333;
                height: 24px;
                line-height: 24px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                background-color: #000;
            }

            .overlay-chart-title span {
                text-align: right;
            }

            .overlay-chart-title .title-name {
                text-align: left;
                font-weight: bold;
            }

            .overlay-chart-title .title-strength,
            .overlay-chart-title .title-change {
                margin-left: 15px;
            }

            .overlay-chart-title .title-limit {
                margin-left: 15px;
                color: #f0f0f0;
            }

            /* 图例样式优化 */
            .overlay-chart .chartjs-legend {
                background-color: rgba(0, 0, 0, 0.5);
                padding: 10px;
                border-radius: 4px;
            }

            /* 切换按钮高亮样式 */
            .chart-type-switch-btn:hover {
                opacity: 0.8;
            }

            .chart-type-switch-btn.active {
                color: #00FFFF !important;
            } 

    </style>
</head>
<body>
    <div class="container">
        <div class="left-panel">
            <div class="block-table-container">
                <table id="blockTable">
                    <thead>
                        <tr>
                            <th data-sort="name">板块</th>
                            <th data-sort="strength">强度</th>
                            <th data-sort="change">涨幅</th>
                            <th data-sort="limit">涨停</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
            <div class="stock-table-container">
                <table id="stockTable">
                    <thead>
                        <tr>
                            <th data-sort="code">代码</th>
                            <th data-sort="name">名称</th>
                            <th data-sort="change">涨幅</th>
                            <th data-sort="continuous">连板</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
        <div class="right-panel">
            <div class="chart-controls">
                <div class="chart-type-switch">
                    <button class="active" data-type="timeline">分时</button>
                </div>
            </div>
            <div class="chart-container" id="chartContainer">
                <!-- 图表将通过JavaScript动态生成 -->
            </div>
        </div>
    </div>
    <script>
        let bankshu=5;  // 每个板块 分时叠加的个股数量
        let bank=10;    //  显示 多少板块数量 
        let ggfenshi=10;   //个股分时图 数量


        // 全局变量
        let currentBlockCode = '';
        let currentSort = {
            block: { field: 'index', direction: 'asc' },
            stock: { field: 'change', direction: 'desc' }
        };
        let showAuctionArea = false;
        let overlayMode = false; // 新增叠加模式标志

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            setupTableSorting();
            setupAuctionButton();
            fetchBlockData();
            setInterval(fetchBlockData, 5000); // 每5秒更新一次板块数据
        });

        // 设置表格排序功能
        function setupTableSorting() {
            document.querySelectorAll('th[data-sort]').forEach(th => {
                th.addEventListener('click', () => {
                    const tableId = th.closest('table').id;
                    const field = th.dataset.sort;
                    const currentDirection = th.getAttribute('data-sort-direction') || 'asc';
                    const newDirection = currentDirection === 'asc' ? 'desc' : 'asc';
                    
                    // 更新当前排序状态
                    currentSort[tableId === 'blockTable' ? 'block' : 'stock'] = {
                        field,
                        direction: newDirection
                    };
                    
                    // 更新表格排序
                    updateTableSort(tableId);
                });
            });
        }

        // 设置竞价按钮
        function setupAuctionButton() {
            const auctionButton = document.createElement('button');
            auctionButton.textContent = '竞价';
            auctionButton.className = 'chart-type-switch-btn';
            auctionButton.style.cssText = `
                background: none;
                border: none;
                color: ${showAuctionArea ? '#00FFFF' : '#fff'};
                cursor: pointer;
                font-size: 14px;
                padding: 2px 8px;
            `;

            auctionButton.onclick = function() {
                showAuctionArea = !showAuctionArea;
                auctionButton.style.color = showAuctionArea ? '#00FFFF' : '#fff';
                const selectedStock = document.querySelector('#stockTable tbody tr.selected');
                if (selectedStock) {
                    fetchStockCharts(selectedStock.dataset.code);
                }
            };

            // 创建叠加按钮
            const overlayButton = document.createElement('button');
            overlayButton.textContent = '叠加';
            overlayButton.className = 'chart-type-switch-btn';
            overlayButton.style.cssText = `
                background: none;
                border: none;
                color: ${overlayMode ? '#00FFFF' : '#fff'};
                cursor: pointer;
                font-size: 14px;
                padding: 2px 8px;
                margin-left: 10px;
            `;

            overlayButton.onclick = function() {
                overlayMode = !overlayMode;
                overlayButton.style.color = overlayMode ? '#00FFFF' : '#fff';
                
                // 根据当前选中的内容更新显示
                if (overlayMode) {
                    // 叠加模式：点击板块时显示叠加图
                    const selectedBlock = document.querySelector('#blockTable tbody tr.selected');
                    if (selectedBlock) {
                        fetchOverlayCharts(selectedBlock.dataset.code);
                    }
                } else {
                    // 普通模式：恢复原有逻辑
                    const selectedStock = document.querySelector('#stockTable tbody tr.selected');
                    if (selectedStock) {
                        fetchStockCharts(selectedStock.dataset.code);
                    }
                }
            };

            const switchContainer = document.querySelector('.chart-type-switch');
            if (switchContainer) {
                switchContainer.appendChild(auctionButton);
                switchContainer.appendChild(overlayButton);
            }
        }

        // 更新表格排序
        function updateTableSort(tableId) {
            const table = document.getElementById(tableId);
            const tbody = table.querySelector('tbody');
            const rows = Array.from(tbody.querySelectorAll('tr'));
            const { field, direction } = currentSort[tableId === 'blockTable' ? 'block' : 'stock'];
            
            rows.sort((a, b) => {
                let aValue = a.dataset[field];
                let bValue = b.dataset[field];
                
                if (field === 'limit') {
                    // 涨停数量排序逻辑
                    aValue = parseInt(aValue) || 0;
                    bValue = parseInt(bValue) || 0;
                    return direction === 'asc' ? aValue - bValue : bValue - aValue;
                } else if (field === 'name') {
                    return direction === 'asc' 
                        ? aValue.localeCompare(bValue, 'zh-CN')
                        : bValue.localeCompare(aValue, 'zh-CN');
                } else if (field === 'index') {
                    return direction === 'asc' ? 
                        parseInt(aValue) - parseInt(bValue) : 
                        parseInt(bValue) - parseInt(aValue);
                } else {
                    aValue = parseFloat(aValue) || 0;
                    bValue = parseFloat(bValue) || 0;
                    return direction === 'asc' 
                        ? aValue - bValue 
                        : bValue - aValue;
                }
            });
            
            tbody.innerHTML = '';
            rows.forEach(row => tbody.appendChild(row));
            
            table.querySelectorAll('th[data-sort]').forEach(th => {
                th.removeAttribute('data-sort-direction');
                if (th.dataset.sort === field) {
                    th.setAttribute('data-sort-direction', direction);
                }
            });
        }

        // 辅助函数：解析连板值
        function parseContinuousValue(value) {
            if (!value) return 0;
            if (value.includes('连板')) {
                return parseInt(value) || 0;
            }
            if (value.includes('天') && value.includes('板')) {
                const matches = value.match(/(\d+)天(\d+)板/);
                if (matches) {
                    return parseInt(matches[2]) || 0;
                }
            }
            if (value === '首板') return 1;
            if (value === '涨停') return 1;
            return 0;
        }

        // 获取板块数据
        async function fetchBlockData() {
            try {
                const blockResponse = await fetch('https://apphq.longhuvip.com/w1/api/index.php?Order=1&a=RealRankingInfo&st=10&apiv=w21&Type=1&c=ZhiShuRanking&PhoneOSNew=1&ZSType=7', {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json'
                    }
                });
                const blockResult = await blockResponse.json();
                // 获取前10个板块，不过滤ST
                const processedBlockData = dataUtils.processBlockData(blockResult).slice(0, 10);

                // 并行获取每个板块的个股数据
                const blockDataPromises = processedBlockData.map(async (block) => {
                    try {
                        const stockResponse = await fetch(`https://apphq.longhuvip.com/w1/api/index.php?Order=1&a=ZhiShuStockList_W8&st=0&c=ZhiShuRanking&PhoneOSNew=1&PlateID=${block.code}&apiv=w35&Type=6`);
                        const stockResult = await stockResponse.json();
                        
                        if (stockResult && stockResult.list && Array.isArray(stockResult.list)) {
                            const stockData = stockResult.list
                                .map(item => {
                                    if (Array.isArray(item) && item.length >= 30) {
                                        return {
                                            code: item[0] || '',
                                            name: item[1] || '',
                                            price: parseFloat(item[5]) || 0,
                                            change: parseFloat(item[6]) || 0,
                                            continuous: item[23] || ''
                                        };
                                    }
                                    return null;
                                })
                                .filter(item => item !== null);

                            // 计算涨停数量
                            const limitCount = stockData.filter(item => isStockLimit(item.continuous)).length;

                            return {
                                ...block,
                                limitCount,
                                stocks: stockData
                            };
                        }
                        return block;
                    } catch (error) {
                        console.error(`获取板块${block.code}个股数据失败:`, error);
                        return block;
                    }
                });

                // 等待所有板块数据获取完成
                const blocksWithStocks = await Promise.all(blockDataPromises);
                updateBlockTable(blocksWithStocks);

                // 如果有选中的板块，更新其个股数据
                const selectedBlock = document.querySelector('#blockTable tr.selected');
                if (selectedBlock) {
                    const selectedBlockData = blocksWithStocks.find(block => block.code === selectedBlock.dataset.code);
                    if (selectedBlockData && selectedBlockData.stocks) {
                        updateStockTable(selectedBlockData.stocks);
                    }
                }
            } catch (error) {
                console.error('获取板块数据失败:', error);
            }
        }

        // 判断股票是否涨停
        function isStockLimit(continuous) {
            if (!continuous) return false;
            return continuous.includes('连板') || 
                continuous.includes('天') && continuous.includes('板') || 
                continuous === '首板';
        }

        // 更新板块表格
        function updateBlockTable(data) {
            if (!Array.isArray(data) || data.length === 0) {
                console.warn('板块数据为空或格式不正确');
                return;
            }

            const tbody = document.querySelector('#blockTable tbody');
            if (!tbody) {
                console.error('未找到板块表格tbody元素');
                return;
            }

            // 获取当前选中的行
            const selectedCode = tbody.querySelector('tr.selected')?.dataset.code;

            data.forEach((item, index) => {
                if (!item) return;
                
                // 查找现有行或创建新行
                let row = tbody.querySelector(`tr[data-code="${item.code}"]`);
                const isNewRow = !row;
                
                if (isNewRow) {
                    row = document.createElement('tr');
                    row.dataset.code = item.code;
                    tbody.appendChild(row);
                }

                // 更新行数据
                row.dataset.name = item.name;
                row.dataset.strength = item.strength;
                row.dataset.change = item.change;
                row.dataset.limit = item.limitCount || '0'; // 添加涨停数据到dataset
                row.dataset.index = index;
                
                const changeValue = parseFloat(item.change);
                const changeClass = changeValue >= 0 ? 'price-up' : 'price-down';
                const changeText = formatUtils.formatChange(changeValue);
                const strengthText = formatUtils.formatStrength(item.strength);
                
                row.innerHTML = `
                    <td>${item.name}</td>
                    <td>${strengthText}</td>
                    <td class="${changeClass}">${changeText}</td>
                    <td>${item.limitCount || 0}</td>
                `;

                // 恢复选中状态
                if (item.code === selectedCode) {
                    row.classList.add('selected');
                }

                // 为新行添加点击事件
                if (isNewRow) {
                    row.addEventListener('click', () => {
                        document.querySelectorAll('#blockTable tbody tr').forEach(tr => {
                            tr.classList.remove('selected');
                        });
                        row.classList.add('selected');
                        currentBlockCode = item.code;
                        
                        // 根据叠加模式决定显示方式
                        if (overlayMode) {
                            // 叠加模式：显示板块和个股叠加图
                            fetchOverlayCharts(item.code);
                        } else {
                            // 普通模式：显示个股列表
                            if (item.stocks) {
                                updateStockTable(item.stocks);
                            } else {
                                fetchStockData(item.code);
                            }
                        }
                    });
                }
            });

            // 删除不在新数据中的行
            Array.from(tbody.children).forEach(row => {
                const code = row.dataset.code;
                if (!data.find(item => item.code === code)) {
                    tbody.removeChild(row);
                }
            });

            // 如果当前排序是按涨停数量，则重新排序
            if (currentSort.block.field === 'limit') {
                updateTableSort('blockTable');
            }
        }

        // 获取个股数据
        async function fetchStockData(blockCode) {
            if (!blockCode) {
                console.warn('板块代码为空');
                return;
            }
            
            try {
                const response = await fetch(`https://apphq.longhuvip.com/w1/api/index.php?Order=1&a=ZhiShuStockList_W8&st=0&c=ZhiShuRanking&PhoneOSNew=1&PlateID=${blockCode}&apiv=w35&Type=6`, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json'
                    }
                });
                const result = await response.json();
                
                if (result && result.list && Array.isArray(result.list)) {
                    const processedData = result.list.map(item => {
                        if (Array.isArray(item) && item.length >= 30) {
                            return {
                                code: item[0] || '',
                                name: item[1] || '',
                                price: parseFloat(item[5]) || 0,
                                change: parseFloat(item[6]) || 0,
                                continuous: item[23] || ''
                            };
                        }
                        return null;
                    }).filter(item => item !== null);
                    
                    // 计算板块涨停数量
                    const limitCount = processedData.filter(item => 
                        !item.name.includes('ST') && isStockLimit(item.continuous)
                    ).length;
                    
                    // 更新板块表格中的涨停数量
                    const blockRow = document.querySelector(`#blockTable tr[data-code="${blockCode}"]`);
                    if (blockRow) {
                        blockRow.dataset.limit = limitCount.toString();
                        blockRow.querySelector('td:last-child').textContent = limitCount.toString();
                    }
                    
                    if (processedData.length > 0) {
                        updateStockTable(processedData);
                    }
                }
            } catch (error) {
                console.error('获取个股数据失败:', error);
            }
        }

        // 更新个股表格
        function updateStockTable(data) {
            const tbody = document.querySelector('#stockTable tbody');
            const selectedCode = tbody.querySelector('tr.selected')?.dataset.code;

            // 获取当前的排序状态
            const { field: sortField, direction: sortDirection } = currentSort.stock;

            // 根据当前排序规则对数据进行排序
            const sortedData = [...data].sort((a, b) => {
                let aValue = a[sortField];
                let bValue = b[sortField];
                
                if (sortField === 'continuous') {
                    // 涨停排序逻辑
                    const aCount = parseContinuousValue(aValue || '');
                    const bCount = parseContinuousValue(bValue || '');
                    return sortDirection === 'asc' ? aCount - bCount : bCount - aCount;
                } else if (sortField === 'name') {
                    return sortDirection === 'asc' 
                        ? aValue.localeCompare(bValue, 'zh-CN')
                        : bValue.localeCompare(aValue, 'zh-CN');
                } else {
                    aValue = parseFloat(aValue) || 0;
                    bValue = parseFloat(bValue) || 0;
                    return sortDirection === 'asc' 
                        ? aValue - bValue 
                        : bValue - aValue;
                }
            });

            // 清空现有数据
            tbody.innerHTML = '';

            // 添加排序后的数据
            sortedData.forEach(item => {
                if (!item || !item.code) return;
                
                const row = document.createElement('tr');
                row.dataset.code = item.code;
                row.dataset.name = item.name;
                row.dataset.change = item.change;
                row.dataset.continuous = item.continuous;
                
                const changeValue = parseFloat(item.change);
                const changeClass = changeValue >= 0 ? 'price-up' : 'price-down';
                const changeText = changeValue.toFixed(2) + '%';
                
                row.innerHTML = `
                    <td>${item.code}</td>
                    <td>${item.name}</td>
                    <td class="${changeClass}">${changeText}</td>
                    <td>${item.continuous || ''}</td>
                `;

                // 恢复选中状态
                if (item.code === selectedCode) {
                    row.classList.add('selected');
                }

                row.addEventListener('click', () => {
                    document.querySelectorAll('#stockTable tr').forEach(tr => tr.classList.remove('selected'));
                    row.classList.add('selected');
                    fetchStockCharts(item.code);
                });

                tbody.appendChild(row);
            });
        }

        // 获取股票图表数据
        async function fetchStockCharts(stockCode) {
            const chartContainer = document.getElementById('chartContainer');
            chartContainer.innerHTML = '';
            chartContainer.classList.remove('overlay-mode'); // 移除叠加模式类
            
            const stockRows = Array.from(document.querySelectorAll('#stockTable tbody tr'));
            const currentIndex = stockRows.findIndex(row => row.dataset.code === stockCode);
            const targetStocks = stockRows.slice(currentIndex, currentIndex + ggfenshi);   //个股 分时数量
            
            for (const stock of targetStocks) {
                try {
                    const marketId = stock.dataset.code.startsWith('6') ? '1' : '0';
                    const response = await fetch(`http://push2his.eastmoney.com/api/qt/stock/trends2/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13&fields2=f51,f52,f53,f54,f55,f56,f57,f58&secid=${marketId}.${stock.dataset.code}`);
                    const result = await response.json();
                    const data = dataUtils.processTimelineData(result);
                    
                    if (data) {
                        const chartDiv = document.createElement('div');
                        chartDiv.className = 'chart';
                        chartContainer.appendChild(chartDiv);
                        
                        const headerDiv = document.createElement('div');
                        headerDiv.className = 'chart-header';
                        headerDiv.innerHTML = `
                            <div class="chart-title">${stock.dataset.name} (${stock.dataset.code})</div>
                            <div class="chart-info">
                                <span class="${parseFloat(stock.dataset.change) >= 0 ? 'price-up' : 'price-down'}">
                                    ${formatUtils.formatChange(stock.dataset.change)}
                                </span>
                            </div>
                        `;
                        chartDiv.appendChild(headerDiv);
                        
                        const canvas = document.createElement('canvas');
                        chartDiv.appendChild(canvas);
                        
                        drawTimelineChart(canvas, data, stock.dataset.name);
                    }
                } catch (error) {
                    console.error('获取图表数据失败:', error);
                }
            }
        }

        // 获取叠加图表数据
        async function fetchOverlayCharts(blockCode) {
            const chartContainer = document.getElementById('chartContainer');
            chartContainer.innerHTML = '';
            chartContainer.classList.add('overlay-mode'); // 添加叠加模式类
            
            try {
                // 获取当前板块在列表中的位置
                const blockRows = Array.from(document.querySelectorAll('#blockTable tbody tr'));
                const currentIndex = blockRows.findIndex(row => row.dataset.code === blockCode);
                
                if (currentIndex === -1) {
                    console.error('未找到当前板块');
                    return;
                }
                
                // 获取从当前板块开始的3个板块
                const targetBlocks = blockRows.slice(currentIndex, currentIndex + bank); //显示的板块分时 数量
                
                // 为每个板块创建叠加图
                for (let i = 0; i < targetBlocks.length; i++) {
                    const blockRow = targetBlocks[i];
                    const currentBlockCode = blockRow.dataset.code;
                    const blockData = {
                        name: blockRow.dataset.name,
                        strength: blockRow.dataset.strength,
                        change: blockRow.dataset.change,
                        limit: blockRow.dataset.limit,
                    };
                    
                    // 创建板块容器，移除间距
                    const blockContainer = document.createElement('div');
                    blockContainer.className = 'block-overlay-container';
                    // blockContainer.style.cssText = `width: 600px; height: 211px;`;
                    chartContainer.appendChild(blockContainer);
                    
                    // 获取板块分时数据
                    const sectorResponse = await fetch(`https://apphq.longhuvip.com/w1/api/index.php?a=GetTrendIncremental&apiv=w31&c=ZhiShuL2Data&StockID=${currentBlockCode}`);
                    const sectorData = await sectorResponse.json();
                    
                    // 获取板块个股列表
                    const stockResponse = await fetch(`https://apphq.longhuvip.com/w1/api/index.php?Order=1&a=ZhiShuStockList_W8&st=0&c=ZhiShuRanking&PhoneOSNew=1&PlateID=${currentBlockCode}&apiv=w35&Type=6`);
                    const stockResult = await stockResponse.json();
                    
                    if (!stockResult || !stockResult.list || !Array.isArray(stockResult.list)) {
                        console.error(`无法获取板块${currentBlockCode}个股数据`);
                        continue;
                    }
                    
                    // 获取前5只个股的数据
                    const stocks = stockResult.list
                        .map(item => {
                            if (Array.isArray(item) && item.length >= 30) {
                                return {
                                    code: item[0] || '',
                                    name: item[1] || '',
                                    change: parseFloat(item[6]) || 0
                                };
                            }
                            return null;
                        })
                        .filter(item => item !== null)
                        .slice(0, bankshu);
                    
                    // 并行获取所有个股的分时数据
                    const stockDataPromises = stocks.map(async (stock) => {
                        const marketId = stock.code.startsWith('6') ? '1' : '0';
                        const response = await fetch(`http://push2his.eastmoney.com/api/qt/stock/trends2/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13&fields2=f51,f52,f53,f54,f55,f56,f57,f58&secid=${marketId}.${stock.code}`);
                        const result = await response.json();
                        return {
                            ...stock,
                            data: dataUtils.processTimelineData(result)
                        };
                    });
                    
                    const stocksWithData = await Promise.all(stockDataPromises);
                    
                    // 处理板块分时数据
                    const processedSectorData = processSectorTimelineData(sectorData);
                    if (processedSectorData) {
                        processedSectorData.name = blockData.name; // 使用板块名称
                    }
                    
                    // 绘制叠加图表
                    drawOverlayChart(blockContainer, processedSectorData, stocksWithData, blockData);
                }
                
            } catch (error) {
                console.error('获取叠加图表数据失败:', error);
            }
        }

        // 处理板块分时数据
        function processSectorTimelineData(data) {
            if (!data || !data.list || !Array.isArray(data.list)) {
                return null;
            }
            
            const preClose = parseFloat(data.preclose_px) || 0;
            const trends = [];
            
            data.list.forEach(item => {
                if (Array.isArray(item) && item.length >= 5) {
                    const time = item[0];
                    const price = parseFloat(item[1]) || 0;
                    const volume = parseFloat(item[3]) || 0;
                    
                    trends.push({
                        time: time,
                        price: price,
                        volume: volume,
                        changePercent: preClose > 0 ? ((price - preClose) / preClose * 100) : 0
                    });
                }
            });
            
            return {
                preClose: preClose,
                trends: trends,
                name: data.stock_name || '板块'
            };
        }

        // 绘制叠加图表
        function drawOverlayChart(container, sectorData, stocksData, blockData) {
            // 创建图表容器，移除内边距以沾满空间
            const chartDiv = document.createElement('div');
            chartDiv.className = 'overlay-chart';
            // chartDiv.style.cssText = 'width: 100%; height: 100%; box-sizing: border-box;';
            container.appendChild(chartDiv);
            
            // 创建标题栏，显示板块详细数据
            const titleBar = document.createElement('div');
            titleBar.className = 'overlay-chart-title';
            const changeValue = parseFloat(blockData.change);
            const changeColor = changeValue >= 0 ? '#ff0000' : '#00ff00';
            const changeText = `${changeValue >= 0 ? '+' : ''}${changeValue.toFixed(2)}%`;
            const strengthText = parseFloat(blockData.strength).toFixed(0);

            titleBar.innerHTML = `
                <span class="title-name">${blockData.name}</span>
                <span class="title-strength">${strengthText}</span>
                <span class="title-change" style="color: ${changeColor};">${changeText}</span>
                <span class="title-limit">${blockData.limit}</span>
            `;
            chartDiv.appendChild(titleBar);

            // 创建图表和图例的容器
            const chartWrapper = document.createElement('div');
            chartWrapper.className = 'chart-wrapper';
            chartDiv.appendChild(chartWrapper);
            
            // 创建canvas并放入容器
            const canvas = document.createElement('canvas');
            chartWrapper.appendChild(canvas);

            // 创建HTML图例容器并放入容器
            const legendContainer = document.createElement('div');
            legendContainer.className = 'html-legend';
            chartWrapper.appendChild(legendContainer);
            
            // 准备数据集
            const datasets = [];
            const stockColors = ['#FFA500', '#00FFFF', '#FF00FF', '#E0E0E0', '#FFFF00']; // 优化颜色：白改为亮灰(#E0E0E0)，避免渲染冲突
            const sectorColor = '#808080';
            
            // 添加板块数据
            if (sectorData && sectorData.trends.length > 0) {
                const filteredTrends = filterTradingTimeTrends(sectorData.trends);
                datasets.push({
                    label: sectorData.name,
                    data: filteredTrends.map(t => ({
                        x: t.time,
                        y: t.changePercent
                    })),
                    borderColor: sectorColor,
                    backgroundColor: sectorColor,
                    borderWidth: 0.5, // 曲线粗细改为0.5
                    pointRadius: 0,
                    tension: 0.1,
                    fill: false,
                    order: 1
                });
            }
            
            // 添加个股数据
            stocksData.forEach((stock, index) => {
                if (stock.data && stock.data.trends) {
                    const filteredTrends = stock.data.trends.filter(t => {
                        const time = t.time.split(' ')[1];
                        const timeNum = Number(time.replace(':', ''));
                        return timeNum >= 930;
                    });
                    
                    datasets.push({
                        label: stock.name,
                        data: filteredTrends.map(t => ({
                            x: t.time.split(' ')[1],
                            y: ((t.price - stock.data.preClose) / stock.data.preClose * 100)
                        })),
                        borderColor: stockColors[index],
                        backgroundColor: stockColors[index],
                        borderWidth: 0.5, // 曲线粗细改为0.5
                        pointRadius: 0,
                        tension: 0.1,
                        fill: false,
                        order: 2 + index
                    });
                }
            });
            
            // 生成自定义HTML图例
            legendContainer.innerHTML = ''; // 清空旧图例
            datasets.forEach(dataset => {
                // 跳过板块数据，不显示在图例中
                if (dataset.borderColor === sectorColor) {
                    return;
                }

                if (!dataset.label) return; // 跳过没有标签的数据集
                const lastPoint = dataset.data.length > 0 ? dataset.data[dataset.data.length - 1] : { y: 0 };
                const changeValue = lastPoint.y;
                const changeColor = changeValue >= 0 ? '#ff0000' : '#00ff00';
                const changeText = `${changeValue >= 0 ? '+' : ''}${changeValue.toFixed(1)}`;

                const legendItem = document.createElement('div');
                legendItem.className = 'legend-item';
                legendItem.innerHTML = `
                    <span class="legend-color-box" style="background-color: ${dataset.borderColor}"></span>
                    <span class="legend-label-name">${dataset.label}</span>
                    <span class="legend-label-change" style="color: ${changeColor}">${changeText}</span>
                `;
                legendContainer.appendChild(legendItem);
            });
            
            // 创建图表
            const chart = new Chart(canvas, {
                type: 'line',
                data: {
                    datasets: datasets
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    animation: false,
                    layout: {
                        padding: {
                            top: 5,
                            right: 15, // 减少右侧内边距，缩小空白
                            bottom: 5,
                            left: 5
                        }
                    },
                    interaction: {
                        mode: 'index',
                        intersect: false
                    },
                    plugins: {
                        legend: {
                            display: false // 禁用默认图例
                        },
                        tooltip: {
                            enabled: true,
                            mode: 'index',
                            intersect: false,
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            titleColor: '#ffffff',
                            bodyColor: '#ffffff',
                            titleFont: { size: 10 },
                            bodyFont: { size: 10 },
                            callbacks: {
                                label: function(context) {
                                    const label = context.dataset.label || '';
                                    const value = context.parsed.y.toFixed(2);
                                    return `${label}: ${value >= 0 ? '+' : ''}${value}%`;
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            type: 'category',
                            grid: {
                                display: false
                            },
                            ticks: {
                                color: '#ffffff',
                                maxRotation: 0,
                                autoSkip: true,
                                callback: function(value, index) {
                                    // 只显示关键时间点
                                    const keyTimes = ['09:30', '10:30', '11:30', '14:00', '15:00'];
                                    return keyTimes.includes(value) ? value : '';
                                },
                                font: { size: 9 }
                            }
                        },
                        y: {
                            position: 'left',
                            grid: {
                                display: true,
                                color: 'rgba(255, 255, 255, 0.05)'
                            },
                            ticks: {
                                color: '#ffffff',
                                font: { size: 9 },
                                callback: function(value) {
                                    return value.toFixed(0) + '%';
                                }
                            }
                        }
                    }
                }
            });
        }

        // 过滤交易时间的分时数据
        function filterTradingTimeTrends(trends) {
            return trends.filter(t => {
                const timeNum = parseInt(t.time.replace(':', ''));
                return (timeNum >= 930 && timeNum <= 1130) || (timeNum >= 1301 && timeNum <= 1500);
            });
        }

        // 绘制分时图
        function drawTimelineChart(canvas, data, stockName) {
            const ctx = canvas.getContext('2d');
            
            const preClose = data.preClose || data.trends[0].avg;
            const prices = data.trends.map(t => t.price);
            const maxPrice = Math.max(...prices);
            const minPrice = Math.min(...prices);
            const priceRange = maxPrice - minPrice;
            const volumes = data.trends.map(t => t.volume);
            const maxVolume = Math.max(...volumes);

            const filteredTrends = showAuctionArea ? data.trends : data.trends.filter(t => {
                const time = t.time.split(' ')[1];
                const timeNum = Number(time.replace(':', ''));
                return timeNum >= 930;
            });

            const avgPrices = filteredTrends.map((t, i) => {
                const totalAmount = filteredTrends.slice(0, i + 1).reduce((sum, item) => sum + item.price * item.volume, 0);
                const totalVolume = filteredTrends.slice(0, i + 1).reduce((sum, item) => sum + item.volume, 0);
                return totalVolume > 0 ? totalAmount / totalVolume : t.price;
            });

            const chart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: filteredTrends.map(t => t.time.split(' ')[1]),
                    datasets: [
                        {
                            label: '分时',
                            data: filteredTrends.map(t => t.price),
                            borderColor: '#ffffff',
                            borderWidth: 1,
                            pointRadius: 0,
                            tension: 0.1,
                            yAxisID: 'price',
                            fill: false
                        },
                        {
                            label: '均价',
                            data: avgPrices,
                            borderColor: '#EBEB00',
                            borderWidth: 1,
                            pointRadius: 0,
                            tension: 0.1,
                            borderDash: [4, 4],
                            yAxisID: 'price',
                            fill: false
                        },
                        {
                            label: '成交量',
                            data: filteredTrends.map(t => t.volume),
                            type: 'bar',
                            yAxisID: 'volume',
                            backgroundColor: (context) => {
                                const index = context.dataIndex;
                                const time = filteredTrends[index].time.split(' ')[1];
                                if (time < '09:30' || (time > '11:30' && time < '13:00')) {
                                    return '#808080';
                                }
                                return filteredTrends[index].price >= (index > 0 ? filteredTrends[index-1].price : preClose) ? '#ff0000' : '#00FFFF';
                            },
                            barPercentage: 0.8,
                            categoryPercentage: 1.0
                        },
                        {
                            label: '昨收',
                            data: Array(filteredTrends.length).fill(preClose),
                            borderColor: '#808080',
                            borderWidth: 1,
                            borderDash: [2, 2],
                            pointRadius: 0,
                            yAxisID: 'price',
                            fill: false
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    animation: false,
                    layout: {
                        padding: {
                            top: 20,
                            right: 5,
                            bottom: 0,
                            left: 5
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            enabled: false
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                color: '#ffffff',
                                maxRotation: 0,
                                autoSkip: true,
                                callback: (value, index) => {
                                    const time = filteredTrends[index]?.time.split(' ')[1];
                                    const keyTimes = ['09:30', '10:30', '11:30', '14:00', '15:00'];
                                    return keyTimes.includes(time) ? time : '';
                                },
                                font: { size: 10 }
                            }
                        },
                        price: {
                            position: 'right',
                            grid: {
                                display: false
                            },
                            ticks: {
                                color: (context) => {
                                    const value = context.tick.value;
                                    if (value === preClose) return '#ffffff';
                                    return value > preClose ? '#ff0000' : '#00FFFF';
                                },
                                font: { size: 10 },
                                callback: (value) => {
                                    if (value === maxPrice || value === minPrice || value === preClose) {
                                        return value.toFixed(2);
                                    }
                                    return '';
                                }
                            },
                            min: minPrice - priceRange * 0.1,
                            max: maxPrice + priceRange * 0.1
                        },
                        percent: {
                            position: 'left',
                            grid: {
                                display: false
                            },
                            ticks: {
                                color: (context) => {
                                    const value = context.tick.value;
                                    if (value === preClose) return '#ffffff';
                                    return value > preClose ? '#ff0000' : '#00FFFF';
                                },
                                font: { size: 10 },
                                callback: value => {
                                    const percent = ((value - preClose) / preClose * 100).toFixed(2);
                                    if (value === maxPrice || value === minPrice || value === preClose) {
                                        return `${percent}%`;
                                    }
                                    return '';
                                }
                            }
                        },
                        volume: {
                            position: 'right',
                            grid: {
                                display: false
                            },
                            ticks: {
                                color: '#ffffff',
                                font: { size: 10 },
                                callback: value => {
                                    if (value === maxVolume) {
                                        return NumberTransform(value);
                                    }
                                    return '';
                                }
                            },
                            min: 0,
                            max: maxVolume * 1.1
                        }
                    }
                }
            });

            // 添加竞价分割线
            if (showAuctionArea) {
                const auctionIndex = filteredTrends.findIndex(t => t.time.split(' ')[1] === '09:30');
                if (auctionIndex !== -1) {
                    const xScale = chart.scales.x;
                    const x = xScale.getPixelForValue(auctionIndex);
                    const chartArea = chart.chartArea;
                    
                    ctx.save();
                    ctx.strokeStyle = '#FFFF00';
                    ctx.setLineDash([2, 2]);
                    ctx.lineWidth = 1;
                    ctx.beginPath();
                    ctx.moveTo(x, chartArea.top);
                    ctx.lineTo(x, chartArea.bottom);
                    ctx.stroke();
                    ctx.restore();
                }
            }
        }

        // 数值转换函数
        function NumberTransform(num) {
            if (Math.abs(num) >= 100000000) {
                return (num / 100000000).toFixed(2) + '亿';
            } else if (Math.abs(num) >= 10000) {
                return (num / 10000).toFixed(2) + '万';
            }
            return num.toString();
        }

        // 添加CSS样式
        const style = document.createElement('style');
        style.textContent = `
        .chart-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px;
            border-bottom: 1px solid #333;
        }

        .chart-header h3 {
            margin: 0;
            font-size: 14px;
        }

        .change {
            font-size: 12px;
            font-weight: bold;
        }

        .change.up {
            color: #00ff00;
        }

        .change.down {
            color: #ff0000;
        }
        `;
        document.head.appendChild(style); 



        //工具脚本
        // 格式化工具函数
        const formatUtils = {
            // 格式化涨幅
            formatChange: (value) => {
                return parseFloat(value || 0).toFixed(2) + '%';
            },
            
            // 格式化强度
            formatStrength: (value) => {
                return Math.round(parseFloat(value || 0));
            },
            
            // 格式化价格
            formatPrice: (value) => {
                return parseFloat(value || 0).toFixed(2);
            },
            
            // 格式化成交量（万手）
            formatVolume: (value) => {
                return (parseFloat(value || 0) / 10000).toFixed(2) + '万';
            },
            
            // 格式化时间
            formatTime: (time) => {
                if (time.length === 5) { // HH:mm格式
                    return time;
                }
                if (time.length === 8) { // HH:mm:ss格式
                    return time.substring(0, 5);
                }
                return time;
            }
        };

        // 数据处理工具
        const dataUtils = {
            // 处理板块数据
            processBlockData: (response) => {
                if (!response || !response.list) return [];
                return response.list.map(item => ({
                    code: item[0],  // 板块代码
                    name: item[1],  // 板块名称
                    strength: item[2], // 板块强度
                    change: item[3],  // 涨跌幅
                    limit: item[4] || 0  // 涨停家数
                })).filter(item => item.code && item.name); // 过滤掉无效数据
            },
            
            // 处理个股数据
            processStockData: (response) => {
                if (!response || !response.data || !response.data.list) return [];
                return response.data.list.map(item => ({
                    code: item[0],  // 股票代码
                    name: item[1],  // 股票名称
                    change: item[6] || 0,  // 涨跌幅
                    continuous: item[23] ? item[23].replace(/"/g, '') : ''  // 去掉连板数据中的双引号
                })).filter(item => item.code && item.name); // 过滤掉无效数据
            },
            
            // 处理分时图数据
            processTimelineData: (response) => {
                if (!response || !response.data || !response.data.trends) return null;
                const trends = response.data.trends.map(trend => {
                    if (typeof trend === 'string') {
                        const [time, price, avg, volume] = trend.split(',');
                        return {
                            time: formatUtils.formatTime(time),
                            price: formatUtils.formatPrice(price),
                            avg: formatUtils.formatPrice(avg),
                            volume: formatUtils.formatVolume(volume)
                        };
                    }
                    return trend;
                });
                return {
                    preClose: response.data.preClose,
                    trends
                };
            },
            
            // 处理K线图数据
            processKLineData: (response) => {
                if (!response || !response.data || !response.data.klines) return null;
                return response.data.klines.map(kline => {
                    if (typeof kline === 'string') {
                        const [date, open, close, high, low, volume] = kline.split(',');
                        return {
                            date,
                            open: formatUtils.formatPrice(open),
                            close: formatUtils.formatPrice(close),
                            high: formatUtils.formatPrice(high),
                            low: formatUtils.formatPrice(low),
                            volume: formatUtils.formatVolume(volume)
                        };
                    }
                    return kline;
                });
            }
        }; 




    </script>
    <!-- 先加载Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> 
     
</body>
</html> 